package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.QiHuiUtil;
import com.block.datapush.service.apipush.utils.SuiBianJieUtil;
import com.block.datapush.service.apipush.utils.WangLuoKeJiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 网络科技
 */
@Service
public class WangLuoKeJiApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    private static final int TOKEN_EXPIRY_DAYS = 29;

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();

        String token = getToken(pushApiKeyParam.getApiKey(), pushApiKeyParam.getApiSecret(), pushApiKeyParam.getInfoId(), pushApiKeyParam.getQueryUrl());


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", memberSourceInfo.getMobileMd5());

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("token", token);


        log.info("【网络科技】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl).headerMap(headerMap, true).body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【网络科技】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        log.info("撞库结果resultObject : {}", resultObject);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channel", pushApiKeyParam.getApiCode());
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("idnum", memberSourceInfo.getIdcard());
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("sex", memberSourceInfo.getSex());
        paramMap.put("zhima_credit", WangLuoKeJiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("has", WangLuoKeJiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("fund", WangLuoKeJiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("house_property", WangLuoKeJiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("car_property", WangLuoKeJiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("marital_status", 2);
        paramMap.put("education", WangLuoKeJiUtil.getxueli(memberSourceInfo.getXueli()));
        paramMap.put("enterprise", WangLuoKeJiUtil.getqiyezhu(memberSourceInfo.getGongzuo()));
        paramMap.put("late", WangLuoKeJiUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("huabei", WangLuoKeJiUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("baitiao", WangLuoKeJiUtil.getbaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("salary", WangLuoKeJiUtil.getsalary(memberSourceInfo.getShouru()));
        paramMap.put("loanAmount", WangLuoKeJiUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loanTime", memberSourceInfo.getLoanTime());


        String token = getToken(pushApiKeyParam.getApiKey(), pushApiKeyParam.getApiSecret(), pushApiKeyParam.getInfoId(), pushApiKeyParam.getQueryUrl());

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("token", token);


        log.info("【网络科技】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl).headerMap(headerMap, true).body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【网络科技】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public String getToken(String account, String password, String id, String requestUrl) {

        String redisKey = StrUtil.format(RedisKeyConstant.MERCHANT_PUSH_TOKEN_KEY, id);
        String token = stringRedisTemplate.opsForValue().get(redisKey);


        if (token == null || token.isEmpty()) {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("account", account);
            paramMap.put("password", password);

            log.info("【网络科技】获取token【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(requestUrl).header("Content-Type", "application/json").body(JSON.toJSONString(paramMap)).execute().body();
            log.info("【网络科技】获取token结束【result】{}", result);


            JSONObject resultObject = JSON.parseObject(result);
            Integer code = resultObject.getInteger("code");
            if (StrUtil.equals(String.valueOf(code), "1")) {
                JSONObject userinfo = resultObject.getJSONObject("data").getJSONObject("userinfo");
                token = userinfo.getString("token");
                stringRedisTemplate.opsForValue().set(redisKey, token, TOKEN_EXPIRY_DAYS, TimeUnit.DAYS);
            }
        }
        return token;
    }

    public static void main(String[] args) {

        String requestUrl = "http://lygxingqu.cn/api/user/login";

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("account", "zhenxiang");
        paramMap.put("password", "123456");

        log.info("【网络科技】获取token【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl).header("Content-Type", "application/json").body(JSON.toJSONString(paramMap)).execute().body();
        log.info("【网络科技】获取token结束【result】{}", result);

        System.out.println(result);

        String token = "";


        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        if (StrUtil.equals(String.valueOf(code), "1")) {
            JSONObject userinfo = resultObject.getJSONObject("data").getJSONObject("userinfo");
            token = userinfo.getString("token");
        }
        System.out.println(token);

    }


}
